package com.hula.onion.book.server.spider.platforms.lujinsuo;

import com.alibaba.fastjson.JSONObject;
import com.hula.onion.book.server.common.CommonResponse;
import com.hula.onion.book.server.common.SpiderCommon;
import com.hula.onion.book.server.config.ResponseStatusEnum;
import com.hula.onion.book.server.model.AccountInfo;
import com.hula.onion.book.server.utils.HttpUtils;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * Description:陆金所spider
 * Create Date:2018/1/17 19:33
 *
 * @author liangbing
 * @version 1.0
 */
@Component("luJinSuoSpider")
public class LuJinSuoSpider extends SpiderCommon {

    private static final String TRUE = "true";

    private static final String LOGIN_SUCCESS_RESULT_ID = "00";

    private static final String CAPTCHA_URL = "https://user.lu.com/user/captcha/captcha.jpg?source=login";

    /**
     * 交易是否需要验证码URL
     */
    private static final String CAPTCHA_AUTHORIZE_URL =
            "https://user.lu.com/user/service/login/captcha-authorize?source=PC&username=";
    /**
     * 登录URL
     */
    private static final String LOGIN_URL = "https://user.lu.com/user/login";
    /**
     * 获取账户信息URL
     */
    private static final String GET_ACCOUNT_INFO_URL = "https://my.lu.com/my/account";

    @Autowired
    private LuJinSuoSpiderHelper luJinSuoSpiderHelper;

    /**
     * 执行爬取操作
     */
    @Override
    public CommonResponse execute() {

        //1.1 组装模拟登陆参数
        HttpClientContext httpContext = HttpClientContext.create();
        BasicCookieStore cookieStore = new BasicCookieStore();
        httpContext.setCookieStore(cookieStore);

        CommonResponse commonResponse = new CommonResponse(ResponseStatusEnum.FAIL);

        //1. 检查是否需要图片验证码
        String captchaJson = HttpUtils.post(CAPTCHA_AUTHORIZE_URL + loginForm.getUserName(), null, httpContext);

        String needCapture = JSONObject.parseObject(captchaJson).get("captcha").toString();

        //需要验证码
        if (TRUE.equals(needCapture) && StringUtils.isEmpty(loginForm.getTicket())) {

            commonResponse = new CommonResponse(ResponseStatusEnum.NEED_CAPTURE);

            return commonResponse;
        }

        //2. 模拟登陆
        Map<String, Object> params =
                luJinSuoSpiderHelper.installRequestParams(loginForm);

//        HttpServletRequest request = loginForm.getRequest();
//        Cookie[] cookies = request.getCookies();
//        if (cookies != null && cookies.length > 0) {
//            for (Cookie cookie : cookies) {
//
//                BasicClientCookie basicClientCookie = new BasicClientCookie(cookie.getName(), cookie.getValue());
//                basicClientCookie.setVersion(0);
//                basicClientCookie.setDomain(".lu.com");
//                basicClientCookie.setPath("/");
//                cookieStore.addCookie(basicClientCookie);
//            }
//        }

        String responseStr = HttpUtils.post(LOGIN_URL, params, httpContext);
        logger.info("[LuJinSuoSpider] Http responseStr result:{}", responseStr.toString());
        LuJinSuoResponseEntity responseEntity = JSONObject.parseObject(responseStr, LuJinSuoResponseEntity.class);

        logger.info("[LuJinSuoSpider] Http response result:{}", responseEntity.toString());

        //登陆成功
        if (LOGIN_SUCCESS_RESULT_ID.equals(responseEntity.getResultId())) {

            //3. 请求账户信息
            String html = HttpUtils.get(GET_ACCOUNT_INFO_URL, httpContext);

            //4. 解析操作
            AccountInfo accountBalance = luJinSuoSpiderHelper.parseAccountBalance(html);

            commonResponse = new CommonResponse(ResponseStatusEnum.SUCCESS);
            commonResponse.setData(accountBalance);

        } else {
            commonResponse.setMsg(responseEntity.getFailedMessage());
            commonResponse.setCode(responseEntity.getResultId());
        }

        return commonResponse;
    }

    @Override
    public String getCaptchaURL() {
        return CAPTCHA_URL;
    }

    @Override
    public String getLoginPageURL() {
        return LOGIN_URL;
    }
}
